<template>
  <header class="sticky top-0 z-10">
    <nav class="bg-white border-gray-200 border-b rounded-lg">
      <div class="max-w-screen-xl flex flex-wrap items-center justify-between mx-auto p-2">
        <a href="/" class="flex items-center">
          <div class="flex items-center justify-center  p-2 bg-white" >
            <img
              :src="blogSettingsStore.blogSettings.logo"
              class="h-8 w-8"
              alt="博客Logo"
            />
            <span class="self-center text-xl font-semibold whitespace-nowrap text-gray-900 ml-2 mr-2">
              {{ blogSettingsStore.blogSettings.name }}
            </span>
          </div>
        </a>

        <div class="flex items-center md:order-2">
          <button
            type="button"
            data-collapse-toggle="navbar-search"
            aria-controls="navbar-search"
            aria-expanded="false"
            class="md:hidden text-gray-900 hover:bg-gray-100 focus:outline-none focus:ring-4 focus:ring-gray-200 rounded-lg text-sm p-2.5 mr-1"
          >
            <svg
              class="w-5 h-5 text-gray-900"
              aria-hidden="true"
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 20 20"
            >
              <path
                stroke="currentColor"
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="m19 19-4-4m0-7A7 7 0 1 1 1 8a7 7 0 0 1 14 0Z"
              />
            </svg>
            <span class="sr-only">Search</span>
            <!-- sr-only: 仅屏幕阅读器可见，普通用户隐藏（用于无障碍访问） -->
          </button>

          <div class="relative hidden mr-2 md:block">
            <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
              <svg
                class="w-4 h-4 text-gray-900"
                aria-hidden="true"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 20 20"
              >
                <path
                  stroke="currentColor"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="m19 19-4-4m0-7A7 7 0 1 1 1 8a7 7 0 0 1 14 0Z"
                />
              </svg>
            </div>
            <input
              type="text"
              id="search-navbar"
              class="block w-full p-2 pl-10 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-blue-500 focus:border-blue-500"
              placeholder="请输入关键词..."
            />
          </div>

          <div
            class="text-gray-900 ml-1 mr-1 hover:text-blue-700 cursor-pointer transition-colors"
            v-if="!isLogined"
            @click="handleNavClick('/login', '登录按钮')"
          >
            登录
          </div>

          <button
            id="dropdownDefaultButton"
            data-dropdown-toggle="dropdown"
            v-else
            class="text-white ml-2 mr-2 md:mr-0 focus:ring-4 focus:ring-blue-300 font-medium rounded-full text-sm text-center inline-flex items-center bg-blue-600 hover:bg-blue-700 focus:ring-blue-800"
            type="button"
          >
            <img
              class="w-8 h-8 rounded-full"
              :src="blogSettingsStore.blogSettings.avatar"
              alt="用户头像"
            />
          </button>

          <div
            id="dropdown"
            class="z-10 hidden bg-white divide-y divide-gray-100 rounded-lg shadow"
          >
            <ul
              class="py-2 text-sm text-gray-900"
              aria-labelledby="dropdownDefaultButton"
            >
              <li>
                <a
                  @click="handleNavClick('/admin/index', '进入后台')"
                  class="block px-4 py-2 hover:bg-gray-100 text-gray-900 hover:text-blue-700"
                >
                  <svg
                    class="inline w-3 h-3 mb-[2px] mr-1 text-gray-700 dark:text-white"
                    aria-hidden="true"
                    xmlns="http://www.w3.org/2000/svg"
                    fill="none"
                    viewBox="0 0 20 20"
                  >
                    <path
                      stroke="currentColor"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M10 14v4m-4 1h8M1 10h18M2 1h16a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1Z"
                    />
                  </svg>
                  进入后台
                </a>
              </li>
              <li>
                <a
                  data-modal-target="popup-modal"
                  data-modal-toggle="popup-modal"
                  class="block px-4 py-2 hover:bg-gray-100 text-gray-900 hover:text-blue-700"
                >
                  <svg
                    class="inline w-3 h-3 mb-[2px] mr-1 text-gray-700 dark:text-white"
                    aria-hidden="true"
                    xmlns="http://www.w3.org/2000/svg"
                    fill="none"
                    viewBox="0 0 16 16"
                  >
                    <path
                      stroke="currentColor"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M4 8h11m0 0-4-4m4 4-4 4m-5 3H3a2 2 0 0 1-2-2V3a2 2 0 0 1 2-2h3"
                    />
                  </svg>
                  退出登录
                </a>
              </li>
            </ul>
          </div>

          <button
            data-collapse-toggle="navbar-search"
            type="button"
            class="inline-flex items-center p-2 w-10 h-10 justify-center text-sm text-gray-900 rounded-lg md:hidden hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-200"
            aria-controls="navbar-search"
            aria-expanded="false"
          >
            <span class="sr-only">Open main menu</span>
            <svg
              class="w-5 h-5 text-gray-900"
              aria-hidden="true"
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 17 14"
            >
              <path
                stroke="currentColor"
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M1 1h15M1 7h15M1 13h15"
              />
              <!-- 三条横线的汉堡菜单图标 -->
            </svg>
          </button>
        </div>

        <div
          class="items-center justify-between hidden w-full md:flex md:w-auto md:order-1"
          id="navbar-search"
        >
          <div class="relative mt-3 md:hidden">
            <!-- 移动端搜索框（中等屏幕以上隐藏） -->
            <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
              <svg
                class="w-4 h-4 text-gray-500 dark:text-gray-400"
                aria-hidden="true"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 20 20"
              >
                <path
                  stroke="currentColor"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="m19 19-4-4m0-7A7 7 0 1 1 1 8a7 7 0 0 1 14 0Z"
                />
              </svg>
            </div>
            <input
              type="text"
              id="search-navbar"
              class="block w-full p-2 pl-10 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-blue-500 focus:border-blue-500"
              placeholder="请输入关键词..."
            />
          </div>

          <ul
            class="flex flex-col p-4 md:p-0 mt-4 font-medium border border-gray-100 rounded-lg bg-gray-50 md:flex-row md:space-x-4 md:mt-0 md:border-0 md:bg-white"
          >
            <li>
              <a
                @click="handleNavClick('/', '首页')"
                :class="
                    currPath === '/'
                     ? 'bg-gradient-to-r from-blue-200 to-blue-300 border-transparent px-8 text-gray-600 font-medium' 
                      : 'text-gray-600 hover:text-blue-700'
                  "
                class="block py-2 px-6 text-center rounded md:bg-transparent mx-2 rounded-full bg-white/80 backdrop-blur-md border border-gray-200 hover:bg-white transition-all"
              >
                首页
              </a>
            </li>
            <li>
              <a
                @click="handleNavClick('/category/list', '分类')"
                :class="
                    currPath === '/category/list'
                     ? 'bg-gradient-to-r from-blue-200 to-blue-300 border-transparent px-8 text-gray-600 font-medium'
                      : 'text-gray-600 hover:text-blue-700'
                  "
                class="block py-2 px-6 text-center rounded md:bg-transparent mx-2 rounded-full bg-white/80 backdrop-blur-md border border-gray-200 hover:bg-white transition-all"
              >
                分类
              </a>
            </li>
            <li>
              <a
                @click="router.push('/tag/list')"
                :class="[currPath == '/tag/list' ? 'bg-gradient-to-r from-blue-200 to-blue-300 border-transparent px-8 text-gray-600 font-medium' : 'text-gray-600']"
                class="block py-2 px-6 text-center rounded hover:bg-gray-100 mx-2 rounded-full bg-white/80 backdrop-blur-md border border-gray-200 hover:bg-white transition-all"
                >标签</a
              >
            </li>

            <li>
              <a
                @click="handleNavClick('/archive/list', '归档')"
                :class="
                    currPath === '/archive/list'
                     ? 'bg-gradient-to-r from-blue-200 to-blue-300 border-transparent px-8 text-gray-600 font-medium'
                      : 'text-gray-600 hover:text-blue-700'
                  "
                class="block py-2 px-6 text-center rounded md:bg-transparent mx-2 rounded-full bg-white/80 backdrop-blur-md border border-gray-200 hover:bg-white transition-all"
              > 归档
              </a>
            </li>
          </ul></div></div>
    </nav>
  </header>

  <!-- 退出登录模态框 -->
  <div
    id="popup-modal"
    tabindex="-1"
    class="fixed top-0 left-0 right-0 z-50 hidden p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-[calc(100%-1rem)] max-h-full"
  >
    <div class="relative w-full max-w-md max-h-full">
      <div class="relative bg-white rounded-lg shadow dark:bg-gray-700">
        <!-- 
                    shadow: 显示阴影
                 -->
        <button
          type="button"
          class="absolute top-3 right-2.5 text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ml-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white"
          data-modal-hide="popup-modal"
        >
          <svg
            class="w-3 h-3"
            aria-hidden="true"
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 14 14"
          >
            <path
              stroke="currentColor"
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6"
            />
            <!-- 关闭按钮的叉号图标 -->
          </svg>
          <span class="sr-only">Close modal</span>
        </button>
        <div class="p-6 text-center">

          <svg
            class="mx-auto mb-4 text-gray-400 w-12 h-12 dark:text-gray-200"
            aria-hidden="true"
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 20 20"
          >
            <!-- 
                            mx-auto: 水平居中
                            mb-4: 底部外边距4个单位（16px）
                            w-12 h-12: 宽高12个单位（48px）
                         -->
            <path
              stroke="currentColor"
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M10 11V6m0 8h.01M19 10a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
            />
            <!-- 警告图标 -->
          </svg>
          <h3 class="mb-5 text-lg font-normal text-gray-500 dark:text-gray-400">
            是否确定退出登录?
          </h3>
          <!-- 
                        mb-5: 底部外边距5个单位（20px）
                        text-lg: 文字大小lg（18px）
                        font-normal: 常规字重（400）
                     -->
          <button
            @click="logout"
            data-modal-hide="popup-modal"
            type="button"
            class="text-white bg-red-600 hover:bg-red-800 focus:ring-4 focus:outline-none focus:ring-red-300 dark:focus:ring-red-800 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2"
          >
            确定
          </button>
          <button
            data-modal-hide="popup-modal"
            type="button"
            class="text-gray-500 bg-white hover:bg-gray-100 focus:ring-4 focus:outline-none focus:ring-gray-200 rounded-lg border border-gray-200 text-sm font-medium px-5 py-2.5 hover:text-gray-900 focus:z-10 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-500 dark:hover:text-white dark:hover:bg-gray-600 dark:focus:ring-gray-600"
          >
            取消
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// 导入Vue核心API
import { onMounted, ref, watch } from 'vue';
// 导入Flowbite组件初始化函数（用于处理交互组件）
import { initCollapses, initDropdowns, initModals } from 'flowbite';
// 导入博客设置的状态管理（获取博客名称、logo等信息）
import { useBlogSettingsStore } from '@/stores/blogsettings';
// 导入用户状态管理（获取登录状态、用户信息等）
import { useUserStore } from '@/stores/user';
// 导入Vue Router相关API（处理路由跳转）
import { useRouter, useRoute } from 'vue-router';
// 导入消息提示工具（显示操作结果提示）
import { showMessage } from '@/composables/util';

/**
 * 组件挂载完成后执行的初始化操作
 * 作用：初始化Flowbite提供的交互组件（折叠菜单、下拉菜单、模态框）
 * 确保这些组件能够正常响应点击等交互事件
 */
onMounted(() => {
  initCollapses(); // 初始化折叠菜单组件（如移动端导航）
  initDropdowns(); // 初始化下拉菜单组件（如用户头像下拉菜单）
  initModals(); // 初始化模态框组件（如退出登录弹窗）
});

// 路由相关处理
const router = useRouter(); // 获取路由实例（用于路由跳转）
const route = useRoute(); // 获取当前路由信息对象（包含路径等信息）

/**
 * 响应式变量：存储当前路由路径
 * 作用：用于判断哪个导航项应该显示高亮状态
 * 初始值为当前路由的路径
 */
const currPath = ref(route.path);
console.log('初始路由路径:', currPath.value); // 调试日志：打印初始路径

/**
 * 导航点击处理函数
 * 作用：统一处理所有导航项的点击事件，添加调试日志并执行路由跳转
 * @param {string} path - 目标路由路径
 * @param {string} name - 导航项名称（用于日志输出）
 */
const handleNavClick = (path, name) => {
  console.log(`点击【${name}】，跳转至:`, path); // 打印点击信息
  router.push(path); // 执行路由跳转
};

/**
 * 监听路由路径变化
 * 作用：当路由发生变化时，更新currPath的值，确保导航高亮状态同步更新
 * 第一个参数：要监听的数据源（当前路由路径）
 * 第二个参数：路径变化后的回调函数
 * { immediate: true }：初始化时立即执行一次（确保初始状态正确）
 */
watch(
  () => route.path,
  (newPath) => {
    console.log('路由变化：', currPath.value, '→', newPath); // 打印路径变化日志
    currPath.value = newPath; // 更新当前路径
  },
  { immediate: true }
);

// 状态管理相关
const blogSettingsStore = useBlogSettingsStore(); // 获取博客设置状态实例
const userStore = useUserStore(); // 获取用户状态实例

/**
 * 响应式变量：存储登录状态
 * 作用：根据用户是否登录，显示不同的界面元素（登录按钮/用户头像）
 * 初始值通过判断用户信息是否为空对象确定
 */
const isLogined = ref(Object.keys(userStore.userInfo).length > 0);
console.log('初始登录状态:', isLogined.value); // 打印初始登录状态

/**
 * 监听登录状态变化
 * 作用：当用户登录状态改变时（登录/退出），更新isLogined的值
 * 确保界面显示与实际登录状态一致
 */
watch(
  () => userStore.userInfo,
  (newInfo) => {
    isLogined.value = Object.keys(newInfo).length > 0; // 更新登录状态
    console.log('登录状态更新:', isLogined.value); // 打印登录状态变化日志
  }
);

/**
 * 退出登录处理函数
 * 作用：执行退出登录操作，更新登录状态并显示提示消息
 */
const logout = () => {
  userStore.logout(); // 调用用户状态的退出登录方法（清除用户信息）
  isLogined.value = false; // 更新登录状态为未登录
  showMessage('退出登录成功'); // 显示操作成功的提示消息
};
</script>
